import {
  UserStore
} from '../../stores/userStore'; // 假设你有一个状态管理
import {
  post,
  get
} from '../../pages/index/request'

const app = getApp();

const CryptoJS = require('../../utils/crypto-js/crypto-js.js');

// // 使用ECB模式加密
function EncryptWithEBC(word) {
  // 唯一秘钥（16个字节，128位）
  const key = CryptoJS.enc.Utf8.parse("EeLMxT42F3qcOpj2");

  // 将要加密的内容转换为Utf8格式
  const srcs = CryptoJS.enc.Utf8.parse(word);

  // 使用AES进行加密，设置ECB模式和填充方式
  const encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB, // 设置为ECB模式
    padding: CryptoJS.pad.Pkcs7 // 填充模式
  });

  // 返回加密后的密文（Base64编码）
  return encrypted.toString();
}

module.exports = {
  EncryptWithEBC
};

Page({
  data: {
    loginForm: {
      username: '',
      password: '',
      usernameType: 0 // 0表示用户名, 1表示邮箱
    },
    forgotPassword: false,
    isShow1: false,
    isShow2: false,
    forgotPasswordForm: {
      mail: '',
      identifyingCode: '',
      newPassword: '',
      confirm: ''
    },
    attempt: 3,
    defaultMessage: '验证失败,您还剩下3次机会',
    fullscreenLoading: false,
    userRoleId: '',
    rememberMe: false,
    userInfo: [],

  },

  // 输入框变化
  onInputChange(e) {
    const {
      name
    } = e.currentTarget.dataset;
    const value = e.detail.value;
    this.setData({
      [name]: value
    });
  },

  // 忘记密码切换
  toggleForgotPassword() {
    this.setData({
      forgotPassword: !this.data.forgotPassword,
      isShow1: false,
      isShow2: false
    });
  },

  // 登录处理逻辑
  async onLogin(e) {
    const username = this.data.loginForm.username
    const password = EncryptWithEBC(this.data.loginForm.password)

    app.globalData.username = username
    app.globalData.password = password

    if (this.data.attempt <= 0) {
      wx.showToast({
        title: '您近期操作频繁,请1分钟后再试',
        icon: 'none'
      });
      return;
    }

    this.setData({
      fullscreenLoading: true
    });

    // 登录请求
    // post('/api/v2/login', { username, password }, 
    post('/api/v2/login', {
        username,
        password
      },

      async (res) => {
          console.log('denglu', res)
          console.log(res.data.accessToken)
          if (res.code === 200) {
            // console.log(res)
            ///////////////////////////////////////////只在测试的时候用
            // wx.navigateTo({
            //   url: '/pages/index/index'
            // });

            /////////////////////////////////////////////////////////
            const accessToken = res.data.accessToken;
            app.globalData.accessToken = accessToken;
            wx.setStorageSync('loginInfo', JSON.stringify(this.data.loginForm));
            await this.getUser(accessToken);
            // console.log('dengliuchengong')
            // console.log(res)
          } else {
            this.onFail(res.msg);
            // console.log('denglushibai')
            wx.showToast({
              title: 'res.msg',
            })
          }
        },
        (error) => {
          this.onFail('发生未知错误，请稍后再试--Login');
          console.log(error);
          console.log(username, password);
        }
    );

    this.setData({
      fullscreenLoading: false
    });
  },

  // 获取用户信息
  async getUser(accessToken) {
    wx.request({
      url: 'http://202.192.19.106:8080/api/v2/users/list?flag=1',
      method: 'POST',
      // header: { 'Authorization': `Bearer ${accessToken}` },
      header: {
        'token': accessToken
      },
      data: {
        'userRoleId': null
      },
      success: (response) => {
        console.log('getUser成功')
        console.log(response)
        const userInfo = response.data.data;
        this.setData({
          userInfo: userInfo

        });
        // 将 userInfo 存储到 globalData
        getApp().globalData.userInfo = userInfo;

        wx.setStorageSync('userInfoLocal', JSON.stringify(this.data.userInfo));
      
        console.log("userInfo", userInfo)
        if (response.data.code === 200) {
          this.setUserInfo(response.data, accessToken);
          // this.redirectUser(response.data.userRoleId);
          console.log("2222222222222222222222222")
          this.redirectUser(accessToken)
          console.log("1111111111111111111111111")
        } else {
          wx.showToast({
            title: response.msg,
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        wx.showToast({
          title: '发生未知错误，请稍后再试--getUser',
          icon: 'none'
        });
        console.log(error);
        console.log("11-error");
        console.log(accessToken);
        console.log("11-error");
      }
    });
  },

  // 设置用户信息
  setUserInfo(userInfo, accessToken) {
    try {
      const userStore = getApp().globalData.userStore;
      console.log("userInfo----",userInfo)
      userStore.setUserProperty('schoolId', userInfo.data.schoolId);
      userStore.setUserProperty('gradeId', userInfo.data.gradeId);
      userStore.setUserProperty('classId', userInfo.data.classId);
      userStore.setUserProperty('districtId', userInfo.data.districtId);
      userStore.setUserProperty('cityId', userInfo.data.cityId);
      userStore.setUserProperty('userRoleId', userInfo.data.userRoleId);
      userStore.setUserProperty('status', userInfo.data.status);
      userStore.setUserProperty('name', userInfo.data.name);
      userStore.setUserProperty('school', userInfo.data.school);
      userStore.setUserProperty('grade', userInfo.data.grade);
      userStore.setUserProperty('className', userInfo.data.className);
      userStore.setUserProperty('city', userInfo.data.city);
      userStore.setUserProperty('district', userInfo.data.district);
      userStore.setUserProperty('mail', userInfo.data.mail);
      userStore.setUserProperty('identityId', userInfo.data.identityId);
      userStore.setUserProperty('number', userInfo.data.number);
      userStore.setUserProperty('phone', userInfo.data.phone);
      userStore.setUserProperty('address', userInfo.data.address);
      userStore.setUserProperty('sex', userInfo.data.sex);
      userStore.setUserProperty('isUse', true);
      userStore.setUserProperty('token', accessToken);
      userStore.setUserProperty('id', userInfo.data.id);
      userStore.setUserProperty('age', userInfo.data.age);
      console.log("userStore使用成功")
    } catch (error) {
      console.log("184", error)
    }
  },

  // 重定向用户
  // redirectUser(userRoleId) {
  //   let redirectUrl = '/nav';
  //   if (userRoleId == 4 || userRoleId == 7) {
  //     redirectUrl = '/student/tests';
  //   } else if (userRoleId == 2) {
  //     redirectUrl = '/school/center/schoolPreview';
  //   } else if (userRoleId == 9) {
  //     redirectUrl = '/teacher/center/SchoolManagement/studentList';
  //   }
  //   wx.redirectTo({
  //     url: redirectUrl
  //   });
  // },

  async redirectUser(accessToken) {
    try {
      await wx.request({
        url: 'http://202.192.19.106:8080/api/v2/users/priv-info',
        method: 'GET',
        data: {
          'flag': 0
        },
        header: {
          'token': accessToken
        },

        success: function(response) {
          console.log("response---",response)
          console.log(response.data.code)
          if (response.data.code === 200) {
            const userStore = getApp().globalData.userStore;
            userStore.setUserProperty('familyType', response.data.data.dataMap.familyType);
            userStore.setUserProperty('nation', response.data.data.dataMap.nation);
            userStore.setUserProperty('motherEdu', response.data.data.dataMap.motherEdu);
            userStore.setUserProperty('siblingRank', response.data.data.dataMap.siblingRank);
            userStore.setUserProperty('fatherEdu', response.data.data.dataMap.fatherEdu);
            userStore.setUserProperty('stay', response.data.data.dataMap.stay);
            console.log(userStore)
            console.log(userStore.User.userRoleId)
            if (userStore.User.userRoleId == 4 || userStore.User.userRoleId ==7) {
              wx.navigateTo({
                url: '/pages/index/index',
              }),
              userStore.User.prompt = true
            } else if (userStore.User.userRoleId == 2) {
              wx.navigateTo({
                url: '/pages/teacherIndex/teacherIndex',
              })
            }
          }
        },
        fail: function(error) {
          console.log("error---",error)
        }
      })
    }catch (error) {
      console.log(error)
    }
  },

  // 登录失败处理
  onFail(msg) {
    this.data.attempt--;
    if (this.data.attempt < 0) {
      wx.setStorageSync('forbid', '1'); // 禁用操作
      wx.showToast({
        title: '操作频繁，请稍后再试',
        icon: 'none'
      });
      return;
    }
    wx.showToast({
      title: msg || this.data.defaultMessage,
      icon: 'none'
    });
    const remainingAttempts = this.data.attempt;
    this.setData({
      defaultMessage: `验证失败,您还剩下${remainingAttempts}次机会`
    });
  },

  // 获取验证码
  async onGetIdentifyingCode(e) {
    const {
      mail
    } = this.data.forgotPasswordForm;
    if (!mail) {
      wx.showToast({
        title: '请输入邮箱',
        icon: 'none'
      });
      return;
    }

    post('/api/v2/users/recovery-password', {
        mail
      },
      (res) => {
        if (res.code === 200) {
          wx.showToast({
            title: '已成功发送验证码,请注意查看',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          });
        }
      },
      (error) => {
        wx.showToast({
          title: '发生未知错误，请稍后再试',
          icon: 'none'
        });
      }
    );
  },

  // 确认密码
  async onConfirmPassword(e) {
    const {
      newPassword,
      confirm
    } = this.data.forgotPasswordForm;
    if (newPassword !== confirm) {
      wx.showToast({
        title: '两次密码不匹配',
        icon: 'none'
      });
      return;
    }

    post('/api/v2/users/recovery-password/verify', {
        mail: this.data.forgotPasswordForm.mail,
        newPassword
      },
      (res) => {
        if (res.code === 200) {
          wx.showToast({
            title: '更改密码成功,您现在可以使用新密码进行登录',
            icon: 'success'
          });
          this.setData({
            forgotPassword: false,
            isShow2: false
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          });
        }
      },
      (error) => {
        wx.showToast({
          title: '发生未知错误，请稍后再试',
          icon: 'none'
        });
      }
    );
  },
  // onUsernameInput(e) {
  //   console.log(e.detail.value)
  // },
  onUsernameBlur(e) {
    // console.log(e.detail.value)
    this.setData({
      'loginForm.username': e.detail.value
    })
    console.log(this.data.loginForm.username)
  },
  onPasswordBlur(e) {
    // console.log(e.detail.value)
    this.setData({
      'loginForm.password': e.detail.value
    })
    console.log(this.data.loginForm.password)
  },

  //点击“记住我”时更新rememberMe的值
  onRememberMeChange: function (e) {
    this.setData({
      rememberMe: e.detail.value
    })
  },
  // 进入登录页面时，如果用户名和密码本地有存储，则填入对应的input中
  onLoad: function () {
    const dataStr = wx.getStorageSync('loginInfo')
    if (dataStr) {
      const data = JSON.parse(dataStr)
      this.setData({
        'loginForm.username': data.username,
        'loginForm.password': data.password,
        'loginForm.usernameType': data.usernameType,
        rememberMe: true
      })
    }
  },
  // 忘记密码
  onForgotPassword: function () {
    this.setData({
      forgotPassword: true
    })
  },
  //忘记密码框中的取消
  onCancel: function () {
    this.setData({
      forgotPassword: false
    })
  }
});